package com.nuanshui.heatedloan.dubbo.extension.filter;

import com.nuanshui.framework.behavior.BehaviorContext;
import com.nuanshui.framework.springContext.Environment;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.DubboTransferConstant;
import com.nuanshui.heatedloan.constant.GlobalParam;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;

import java.util.ArrayList;
import java.util.List;

public class AccessFilter implements Filter {

	private static Logger log = LoggerFactory.getLogger(AccessFilter.class);

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation)
			throws RpcException {

//		if(!Environment.isRestEnv())
//		{
//			BehaviorContext.removeContext();
//		}


		traceLogUnique();
		traceUserInfo();
        Result result =  invoker.invoke(invocation);   
        return result;
	}

	/*
	* 传递unique
	*
	* */
	private void traceLogUnique()
	{
		if(RpcContext.getContext().isConsumerSide())
		{
			String unique = MDC.get("unique");
			if(StringUtils.isNotEmpty(unique)){
				RpcContext.getContext().setAttachment("unique", unique); //设置到RPCZ中
			}
		}

		if(RpcContext.getContext().isProviderSide())
		{
			String unique = RpcContext.getContext().getAttachment("unique");
			if(StringUtils.isNotEmpty(unique)){
				MDC.put("unique",unique);
			}
		}
	}

	//消费者应该把参数告诉提供者
	//提供者应该把消费者的信息保存起来
	/*
	* 传递用户信息
	*
	* */
	private void traceUserInfo()
	{

		List<String> list=new ArrayList<>();
		list.add(DubboTransferConstant.DUBBO_SERVER_CURRENTUSER);
		list.add(DubboTransferConstant.DUBBO_SERVER_USERID);
		list.add(GlobalParam.USER_AGENT);
		list.add(DubboTransferConstant.DUBBO_SERVER_OPENID);

		if(RpcContext.getContext().isConsumerSide())
		{
			for (String key:list) {
				String strUserInfo = (String)BehaviorContext.getContext().get(key);

				if(StringUtils.isNotEmpty(strUserInfo)){
					RpcContext.getContext().setAttachment(key,strUserInfo);
				}
			}
		}

		if(RpcContext.getContext().isProviderSide())
		{
			BehaviorContext.removeContext();
			for (String key:list) {
				String strUserInfo = RpcContext.getContext().getAttachment(key);

				if(StringUtils.isNotEmpty(strUserInfo)){
					BehaviorContext.getContext().put(key,strUserInfo);
				}
			}
		}
	}

}
